<?php

class ProjectController extends Controller
{
	
   /**
    * Set layout
   */
   public $layout = '//layouts/cms/main';
   
   /**
	 * action array filter
	 */
   public function filters()
	{
		return array(
         'accessControl', // perform access control for CRUD operations
      );
	}
   
   /**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
   public function accessRules(){
      $rights = Role::getRights($this->id);
      return $rights;
   }
   
   /**
	 * Check login all action
	 */
   public function beforeAction($action){
      if(is_null(Yii::app()->user->id))
         $this->redirect('/admin/default/login');
      else
         return true;
   }
   
   /**
    * Display page index
   */
   public function actionIndex()
	{
	     
		$page = Yii::app()->request->getParam('page',1); // Lấy số trang
      $limit = Yii::app()->request->getParam('limit',10); // Lấy số dòng hiển thị trên grid
      $sidx = isset($_GET['sidx']) ?  $_GET['sidx'] : 'prj_date_create'; // Lấy trường cần sắp xếp
      $sord = isset($_GET['sord']) ? $_GET['sord'] : 'DESC'; // Lấy giá trị muốn sắp xếp
      $start = $limit*$page - $limit; // Thứ tự bản ghi bắt đầu lấy
      $rowList = array(10,20,30,50,100);  
      //Biến xác định phiên làm việc của user
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;  
      $list = array();
      $model = new Project();
      $model->unsetAttributes();
      
      $criteria = new CDbCriteria;
      $criteria->limit = $limit;
      $criteria->offset = $start;
      $criteria->order = $sidx . ' ' . $sord;
      if(isset($_POST['Project'])){ // Nếu người dùng search
         $model->attributes = $_POST['Project'];
         $params = array();
         
         if(isset($_POST['start_date'])){
            $criteria->addCondition("prj_date_create >= :start_date", "AND");
            $params[':start_date'] = strtotime(str_replace('/','-',$_POST['start_date']));
         }
         if(isset($_POST['end_date'])){
            $criteria->addCondition("prj_date_create <= :end_date", "AND");
            $params[':end_date'] = strtotime(str_replace('/','-',$_POST['end_date'])) + 86400; //Cuối ngày
         }
         if($model->prj_name != ''){
            $criteria->addCondition("prj_name like :prj_name", "AND");
            $params[':prj_name'] = '%'.$model->prj_name.'%';
         }
         if($model->prj_active != 2){
            $criteria->addCondition("prj_active = :prj_active", "AND");
            $params[':prj_active'] = $model->prj_active;
         }
            
         $criteria->params = $params;
         $object = $model->with('district','province')->findAll($criteria);
      }else{
         $object = $model->with('district','province')->findAll($criteria);   
      }
      if(count($object) > 0){
         foreach($object as $item){
            $list[$item->attributes['prj_id']] = $item->attributes;
            $list[$item->attributes['prj_id']]['dis_name'] = !is_null($item->getRelated('district')) ? $item->getRelated('district')->attributes['dis_name'] : "Chưa rõ";
            $list[$item->attributes['prj_id']]['prv_name'] = !is_null($item->getRelated('province')) ? $item->getRelated('province')->attributes['prv_name'] : "Chưa rõ";
         }
      }
      $total_record = $model->count($criteria); // Đếm tổng số bản ghi
      if( $total_record >0 ) {
      	$total_pages = ceil($total_record/$limit);
      } else {
      	$total_pages = 0;
      }
      
      //Danh sach tinh thanh
      $list_province = array(0 => '-- Tỉnh/TP --'); // Danh sách các Tỉnh/Tp
      $province = new Province();
      $object = $province->findAll(array(
         'order' => 'prv_order DESC, prv_name ASC',
      ));
      
      //Danh sach danh muc
      $list_category = array();
      $category = new Category();
      $all_cate = $category->getAll();
      $tree_cate = $category->getTree($all_cate);
      
      if(count($object) > 0){
         foreach($object as $item){
            $list_province[$item->attributes['prv_id']] = $item->attributes['prv_name'];
         }
      }
      
      $list_district = array(0 => '-- Quận/Huyện --');
      if($model->prj_prv_id > 0){
         $object = District::model()->getAllByPrvID($model->prj_prv_id);
         foreach($object as $item){
            $list_district[$item['dis_id']] = $item['dis_name'];
         }
      }
      
      
      $list_project = array(0 => '-- Dự án --');
      if($model->prj_prv_id > 0){
         $object = Project::model()->findAllByAttributes(array('prj_dis_id' => $model->prj_dis_id));
         foreach($object as $item){
            $list_project[$item['prj_id']] = $item['prj_name'];
         }
      }
      
      $this->render('index',array("model" => $model,
                                  "session_user" => $session_user,
                                  "list" => $list,
                                  "rowList" => $rowList,
                                  "page" => $page,
                                  "start" => $start,
                                  "limit" => $limit,
                                  "total_record" => $total_record,
                                  "total_pages" => $total_pages,
                                  'list_province' => $list_province,
                                  'list_district' => $list_district,
                                  'list_project' => $list_project,
                                  'tree_cate' => $tree_cate,));
	}
   
   /**
    * 
    * Display page create
   */
   public function actionCreate(){
      $model = new Project();
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['Project'])){
         $model->attributes = $_POST['Project'];
         $model->prj_date_create = time();
         if($model->validate()){
            if($model->save()){
               $message = "Tạo dự án thành công";   
               if($action_user == 'save'){
                  $this->redirect('/index.php/admin/'.$this->id);
               }
            }  
         }
      }
      //Danh sach tinh thanh
      $list_province = array(0 => '-- Tỉnh/TP --'); // Danh sách các Tỉnh/Tp
      $province = new Province();
      $object = $province->findAll(array(
         'order' => 'prv_order DESC, prv_name ASC',
      ));
      
      if(count($object) > 0){
         foreach($object as $item){
            $list_province[$item->attributes['prv_id']] = $item->attributes['prv_name'];
         }
      }
      $this->pageTitle = 'Thêm mới dự án';
      $this->layout = '//layouts/cms/create';
      $this->render('create',array('model'=>$model,
                                    'session_user' => $session_user,
                                    'list_province' => $list_province,

                                    'message' => $message));
   }
   
   /**
    * 
    * Get all district by prv_id
   */
   public function actionSetDropListByDisID($dis_id){
      $option = array(0 => '-- Dự án --');
      if($dis_id > 0){
         $model = new Project();
         $object = $model->findAllByAttributes(array('prj_dis_id' => $dis_id));
         if(count($object) > 0){
            foreach($object as $item){
               $option[$item->attributes['prj_id']] = $item->attributes['prj_name'];
            }
         }
      }
      foreach($option as $key=>$value){
         echo '<option value="'.$key.'">'.$value.'</option>';
      }
   }

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}